package com.hyf.rabbitmq.helloWorld;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Send {

    //为队列起个name
    private static String QUEUE_NAME="hello";

    public static void main(String[] args){
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setUsername("admin");
        factory.setPassword("12345");
        factory.setVirtualHost("/");
        factory.setPort(5672);
        //第二种连接方式
        //factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost");
        Connection connection =null;
        Channel channel=null;
        try {
             connection = factory.newConnection();
             channel = connection.createChannel();

            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            String message="hello world!";
            for(int i=0;i<10;i++){
                message=message+"i";
                TimeUnit.MILLISECONDS.sleep(200);
                channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
                System.out.println(String.format("[x] Send %s",message));
            }


        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{
            /*if(channel!=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
        }

    }

}
